import os
import winreg


def get_desktop_path():
    """获取桌面路径"""

    key = winreg.OpenKey(
        winreg.HKEY_CURRENT_USER,
        r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
    return winreg.QueryValueEx(key, 'Desktop')[0]


def choose_file(path=get_desktop_path()):
    """
    获取选择文件的路径
    :param path 打开的起始路径 默认桌面路径
    """
    import win32ui

    dlg = win32ui.CreateFileDialog(True)  # file-dialog
    dlg.SetOFNInitialDir(path)  # start path
    dlg.DoModal()  # implement
    file_name = dlg.GetPathName()  # wait for choosing . . .
    return file_name  # the value will be '' if close the window


def split_path(p_1, p_2):
    """路径拼接"""
    from os import path

    if isinstance(p_1, str) and isinstance(p_2, str):
        if p_1 == p_2 == '':
            return 0
        else:
            return path.normpath(path.join(p_1, p_2))  # 自动将多余的 \\ \/ // /\ 转换成 '\\'
    return 0


def reset_dir(abs_path, mode=1):
    """
    不递归清除目录下的文件 文件夹不存在则自动创建
    :param abs_path 绝对路径
    :param mode 设置模式 1执行删除 0跳过删除 默认触发创建
    """
    from os.path import exists
    from os import listdir, remove, mkdir
    from core.sysuser import split_path
    from extensions import log_err

    def done_loop(path):
        if mode not in [0, 1]:
            return 0
        if exists(path):
            if mode == 1:  # 模式1执行删除 模式0跳过
                for file_n in listdir(path):
                    remove(split_path(path, file_n))
        else:
            try:
                mkdir(path)  # 默认触发创建最后一级目录
            except Exception as e:
                log_err.set_log_message('ERROR')  # 写入日志 默认以warning级别写入
                return 0
        return 1

    if isinstance(abs_path, str):
        return done_loop(abs_path)
    elif isinstance(abs_path, list):
        for p in abs_path:
            if done_loop(p) == 0:
                return 0
        return 1
    else:
        return 0


if __name__ == '__main__':
    pass
